package com.sanctuary.dao.impls;

import java.sql.SQLException;
import java.util.List;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.sanctuary.dao.interfaces.UserDao;
import com.sanctuary.models.User;

public class UserDaoImpl extends SqlMapClientDaoSupport implements UserDao {

	public User authenticate(User u) throws SQLException {
		User _u = (User) getSqlMapClientTemplate().queryForObject("authenticate-user",u);
		if (_u == null) {
			return null;
		} else {
			return _u;
		}
	}

	public int delete(User u) throws SQLException {
		return getSqlMapClientTemplate().delete("delete-user",u);
	}

	public List<User> findActive() throws SQLException {
		return (List<User>) getSqlMapClientTemplate().queryForList("findActive-users");
	}

	public User findByEmail(String email) throws SQLException {
		return (User) getSqlMapClientTemplate().queryForObject("findByEmail-user",email);
	}

	public User findById(int id) throws SQLException {
		User u = new User();
		u.setId(id);
		return (User) getSqlMapClientTemplate().queryForObject("findById-user",u);
	}

	public int save(User u) throws SQLException {
		if (u.getId() == 0) {
			// new user, insert
			return ((User) getSqlMapClientTemplate().insert("insert-user",u)).getId();
		} else {
			// existing user, update
			return getSqlMapClientTemplate().update("update-user",u);
		}
	}

	public User findByUsername(String username) throws SQLException {
		User _u = (User) getSqlMapClientTemplate().queryForObject("findByUsername-user",username);
		if (_u == null) {
			return null;
		} else {
			return _u;
		}
	}
	

}
